package org.monkey.socket.plugin.config;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import java.util.Properties;
import lombok.extern.slf4j.Slf4j;
import org.monkey.socket.plugin.entity.WebSocketProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

@Slf4j
@ConditionalOnClass(name = "com.alibaba.nacos.api.naming.NamingService")
@ConditionalOnProperty(value = "spring.cloud.nacos.discovery.enabled",havingValue = "true")
@AutoConfiguration
public class NacosRegisterBean implements CommandLineRunner {
  @Autowired
  WebSocketProperties webSocketProperties;
  @Value("${spring.cloud.nacos.discovery.server-addr}")
  private String serverAddr;
  @Value("${spring.cloud.nacos.discovery.namespace}")
  private String namespace;
  @Value("${spring.cloud.nacos.discovery.group:DEFAULT}")
  private String group;
  @Override
  public void run(String... args){
    Properties properties = new Properties();
    properties.put("namespace",namespace);
    properties.put("serverAddr",serverAddr);
    properties.put("username","nacos");
    properties.put("password","monkey@123");
    try {
      String clustomerName = "DEFAULT";
      String id = String.format("%s#%s#%s#%s@@%s",webSocketProperties.getHost(),webSocketProperties.getPort(),clustomerName,group,webSocketProperties.getNacosName());
      Instance instance = new Instance();
      instance.setClusterName(clustomerName);
      instance.setEnabled(true);
      instance.setIp(webSocketProperties.getHost());
      instance.setPort(webSocketProperties.getPort());
      instance.setServiceName(webSocketProperties.getNacosName());
      instance.setInstanceId(id);
      //获取nacos服务
      NamingService namingService = NamingFactory.createNamingService(properties);
      //将服务注册到注册中心
      namingService
            .registerInstance(webSocketProperties.getNacosName(),group,instance);
        log.info("netty service register to nacos success");
    } catch (NacosException e) {
      log.error("注册nacos失败", e);
    }

  }
}
